package org.hepeng.workx.spring.session.redis.serializer;

import net.bytebuddy.dynamic.loading.ByteArrayClassLoader;
import org.joor.Reflect;
import org.springframework.core.serializer.DefaultDeserializer;
import org.springframework.core.serializer.support.DeserializingConverter;
import org.springframework.data.redis.serializer.RedisSerializer;

import java.util.HashMap;
import java.util.Map;

/**
 * @author he peng
 */
public class JdkSerializationSafetyClassBytesHandler extends AbstractSafetyRedisHttpSessionMessageReceiver {

    public JdkSerializationSafetyClassBytesHandler(RedisSerializer redisSerializer) {
        super(redisSerializer);
    }

    @Override
    protected void handleClassBytes(String className , byte[] classBytes) {
        DeserializingConverter converter = Reflect.on(this.serializer).get("deserializer");
        DefaultDeserializer deserializer = Reflect.on(converter).get("deserializer");
        Object oldClassLoader = Reflect.on(deserializer).get("classLoader");
        Map<String, byte[]> oldTypeDefinitions = Reflect.on(oldClassLoader).get("typeDefinitions");
        Map<String, byte[]> typeDefinitions = new HashMap<>(oldTypeDefinitions);
        typeDefinitions.put(className , classBytes);
        ByteArrayClassLoader classLoader =
                new ByteArrayClassLoader(ClassLoader.getSystemClassLoader(), typeDefinitions);
        Reflect.on(deserializer).set("classLoader" , classLoader);
    }

}
